package corm

import (
	"context"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm/logger"
	"time"
)

type GormLogger struct {
	Log *logrus.Logger
}

func NewGormLogger(log *logrus.Logger) *GormLogger {
	return &GormLogger{Log: log}
}

// 实现 LogMode 方法，设置日志级别
func (g *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
	newLogger := *g
	switch level {
	case logger.Silent:
		newLogger.Log.SetLevel(logrus.PanicLevel)
	case logger.Error:
		newLogger.Log.SetLevel(logrus.ErrorLevel)
	case logger.Warn:
		newLogger.Log.SetLevel(logrus.WarnLevel)
	case logger.Info:
		newLogger.Log.SetLevel(logrus.InfoLevel)
	}
	return &newLogger
}

// Info 级别日志
func (g *GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
	g.Log.Infof(msg, data...)
}

// Warn 级别日志
func (g *GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
	g.Log.Warnf(msg, data...)
}

// Error 级别日志
func (g *GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
	g.Log.Errorf(msg, data...)
}

// Trace 用于记录执行 SQL 的详细信息
func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	elapsed := time.Since(begin)
	sql, rows := fc()

	if err != nil {
		//g.Log.
		g.Log.WithFields(logrus.Fields{
			"duration": elapsed,
			"rows":     rows,
			"sql":      sql,
		}).Errorf("SQL 执行错误: %v", err)
	} else {
		g.Log.WithFields(logrus.Fields{
			"duration": elapsed,
			"rows":     rows,
			"sql":      sql,
		}).Info("SQL 执行完成")
	}
}
